import { Component } from "react";
import { View, Text, Image } from "@tarojs/components";
import { ConfigItem, NavBarProps, NavBarState } from "./type";

import "./index.less";

export class NavBar extends Component<NavBarProps, NavBarState> {
  constructor(props) {
    super(props);
    const { activeId, config = [] } = props;
    this.state = {
      activeId: activeId
        ? config.find(item => item.id === activeId)?.id
        : config[0]?.id
    };
  }

  handleItemClick = (item: ConfigItem) => {
    const { onChange } = this.props;
    this.setState({
      activeId: item.id
    });
    onChange && onChange(item);
  };

  renderItems = () => {
    const { config = [], activeId } = this.props;
    return config.map(item => {
      const { title, id, icon, activeIcon } = item;
      const imgSrc =
        (activeId || this.state.activeId) === id ? activeIcon : icon;
      return (
        <View
          className="navbar-item-wrap"
          key={id}
          onClick={() => this.handleItemClick(item)}
        >
          <View className="navbar-icon-wrap">
            <Image className="icon" src={imgSrc} />
          </View>
          <View className="navbar-title-wrap">
            <Text>{title}</Text>
          </View>
        </View>
      );
    });
  };
  render() {
    const items = this.renderItems();
    return <View className="navbar-wrap">{items}</View>;
  }
}

export default NavBar;
